  

import { ref } from 'vue'
import type { Ref } from 'vue'
import type { Graph } from '@antv/x6'
import { genTaskCodeList } from '@/service/modules/task-definition'
import { Coordinate, Dragged } from './types'
import { TaskType } from '@/views/projects/task/constants/task-type'
import { useRoute } from 'vue-router'

interface Options {
  readonly: Ref<boolean>
  graph: Ref<Graph | undefined>
  appendTask: (code: number, type: TaskType, coor: Coordinate) => void
}

/**
 * Sidebar item drag && drop in canvas
 */
export function useDagDragAndDrop(options: Options) {
  console.log('useDagDragAndDrop--->')
  console.log('options->',options);
  
  const { readonly, graph, appendTask } = options

  const route = useRoute()
  // const projectCode = Number(route.params.projectCode)

  // The element currently being dragged up
  const dragged = ref<Dragged>({
    x: 0,
    y: 0,
    type: 'SHELL'
  })

  function onDragStart(e: DragEvent, type: TaskType) {
    console.log('onDragStart---')
    if (readonly.value) {
      e.preventDefault()
      return
    }
    dragged.value = {
      x: e.offsetX,
      y: e.offsetY,
      type: type
    }
  }

  function onDrop(e: DragEvent) {
    console.log('onDrop---')
    e.stopPropagation()
    e.preventDefault()
    if (readonly.value) {
      return
    }
    if (dragged.value && graph.value) {
      const { type, x: eX, y: eY } = dragged.value
      const { x, y } = graph.value.clientToLocal(e.clientX, e.clientY)
      const genNums = 1
      let random1 = Math.floor(Math.random()* 15000000)
      appendTask( random1, type, { x: x - eX, y: y - eY })
      // genTaskCodeList(genNums, projectCode).then((res) => {
      //   const [code] = res
      //   appendTask(code, type, { x: x - eX, y: y - eY })
      // })
    }
  }

  const preventDefault = (e: DragEvent) => {
    e.preventDefault()
  }

  return {
    onDragStart,
    onDrop,
    onDragenter: preventDefault,
    onDragover: preventDefault,
    onDragleave: preventDefault
  }
}
